package com.xzz.mybatis.generator.utils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * your Description
 */
@UtilityClass
@Slf4j
public class MyFileUtil {

    public static final String IMPORT_TMP_DIR = "imports";
    public static final String FILE_SEPERATOR = "/";
    public static final Long EXPIRED_IN_7_DAYS = 604800L;



    /**
     * 把MultipartFile 写到临时目录，否则跳线程后，无法拿到文件，因为MultipartFile已经被controller线程关闭
     * @param file
     * @return
     */
    public static File writeMultipartFileToTmpDir(MultipartFile file){
        try{
            File retFile = createTmpFile(file.getOriginalFilename());
            file.transferTo(retFile);
            return retFile;
        }catch (Exception e){
            log.warn("writeMultipartFileToTmpDir error", e);
        }
        return null;
    }

    private static File createTmpFile(String fileName) throws IOException {
        StringBuilder newFileAbsPath = new StringBuilder();
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){ //windows下, inellij下, / 开始的目录不知道为什么解析错误, 加个盘符试试
            newFileAbsPath.append("C:/");
        }
        newFileAbsPath.append("tmp");
        if(!"tmp".endsWith("/")){
            newFileAbsPath.append(FILE_SEPERATOR);
        }
        //C:\tmp\imports
        newFileAbsPath.append(IMPORT_TMP_DIR).append(FILE_SEPERATOR);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-hhmmss-");
        newFileAbsPath.append("user-date-"+simpleDateFormat.format(new Date())).append(fileName);
        File tmpFile = new File(newFileAbsPath.toString());
        FileUtils.touch(tmpFile);
        return tmpFile;
    }






}
